/**
 * 级联select组件
 */
layui.define(['form'], function(exports){
	var $ = layui.jquery
	,form = layui.form();

	//加载州/地区/城市选择
	$.each($(".state"), function(i, e){
		buildMultiState(e);	
	});
	
	//生成多选择
	function buildMultiState(e, family) {
		var _self = $(e);
								
		if(null == family) {
			if(typeof(_self.attr("family")) == "undefined") {
				return;	 
			}
			family = _self.attr("family");
			if("" == family) {
				_self.val("");
			}
		}
				
		if("" == _self.val()) {
			$.getJSON("/web/state", function(json){
				var select = "<div class=\"layui-input-inline\"><select lay-filter=\"state\">";
				select += "<option value=\"0\">请选择 </option>";
				$(json).each(function(){
					select += "<option family=\"" + this.family + "\" value=\"" + this.id + "\" >" + this.value + "</option>";
				});
				select += "</select></div>";
				_self.after(select);
				
				form.render('select');
			});
			
			return;
		}
		
		var familys = family.split(",");
		
		$.each(familys, function(k, v){
			if(null != v && "" != v) {
				var url = 0 == k ? "/web/state" : "/web/state?id=" + familys[k-1];
				$.getJSON(url, function(json){
					var select = "<div class=\"layui-input-inline\"><select lay-filter=\"state\">";
					select += "<option value=\"0\">请选择 </option>";
					$(json).each(function(){
						select += "<option value=\"" + this.id + "\"";
						if(v == this.id) {
							select += " selected=\"selected\" ";
						}
						select += ">" + this.value + "</option>";
					});
					select += "</select></div>";
					_self.after(select);
					
					form.render('select');
				});
			}			
		});		
	}
	
	form.on('select(state)', function(data){		
		var _self = $(data.elem);
		var state = _self.closest("div").siblings(".state").eq(0);
		
		/*重新清理后面元素*/
		if(null != _self.closest("div").nextAll()) {
			_self.closest("div").nextAll().each(function(){
				this.remove();
			});
		}
		
		if(0 == _self.val()) {
			return;
		}
		
		$.getJSON("/web/state?id=" + _self.val(), function(json){
			if(null != json && eval(json).length != 0) {			
				state.val("");
				state.attr("family", "");			
				var select = "<div class=\"layui-input-inline\"><select lay-filter=\"state\">";
				select += "<option value=\"0\">请选择 </option>";
				$(json).each(function(){
					select += "<option family=\"" + this.family + "\" value=\"" + this.id + "\">" + this.value + "</option>";
				});
				select += "</select></div>";
				_self.closest("div").after(select);			
			} else {
				state.val(_self.val());
				state.attr("family", _self.find("option:selected").attr("family"));
			}
			
			form.render('select');
		});		
	});

	exports('select', gather);
});